/**
 * created by 小卷毛, 2021-07-09
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl.viewmodel

import android.graphics.Color
import com.lzg.extend.BaseResponse
import com.lzg.extend.JsonConvert
import com.lzg.extend.jackson.JacksonConvert
import com.lzg.okrx.adapter.FlowableBody
import com.lzy.okgo.OkGo
import com.rzico.sbl.R
import com.rzico.sbl.model.*
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.applyFlowableSchedulers
import com.xinnuo.common_ui.utils.subscribeByFinally

/**
 * 描 述：配送联盟统计操作相关
 * 作 者：小卷毛  2021-07-09 10:55
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class StatisticUnionViewModel : DialogViewModel() {

    fun unionIcons() = arrayListOf(
        ManagerDivider("结算"),
        ManagerContent("结算统计", R.mipmap.icon_union04),
        ManagerContent("订单统计", R.mipmap.icon_union05),
        ManagerContent("商品统计", R.mipmap.icon_union06),
        ManagerContent(),
        ManagerDivider("配送"),
        ManagerContent("配送结算", R.mipmap.icon_union02),
        ManagerContent(),
        ManagerContent(),
        ManagerContent(),
        ManagerDivider("空桶"),
        ManagerContent("空桶结算", R.mipmap.icon_union03),
        ManagerContent(),
        ManagerContent(),
        ManagerContent(),
        ManagerDivider()
    )

    fun settleColor() = arrayListOf(
        Color.rgb(36, 134, 248),
        Color.rgb(167, 95, 234)
    )

    val mTypeList by lazy {
        listOf(
            FilterData("转出订单", "out", "转出订单"),
            FilterData("接收订单", "in", "接收订单")
        )
    }

    val mTypeGoods by lazy {
        listOf(
            FilterData("转出商品", "out", "转出商品"),
            FilterData("接收商品", "in", "接收商品")
        )
    }

    val mFilterTime by lazy {
        listOf(
            FilterData("今日", "1", "今日"),
            FilterData("昨日", "2", "昨日"),
            FilterData("近7天", "3", "近7天"),
            FilterData("本月", "4", "本月"),
            FilterData("上月", "5", "上月"),
            FilterData("本年", "6", "本年"),
            FilterData("自定义时间", "7", "自定义")
        )
    }

    /**
     * 配送结算列表
     */
    fun sendList(
        beginDate: String,
        endDate: String,
        onSuccess: (ResponseModel<UnionSendTotal>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ResponseModel<UnionSend>>>(BaseUrl.unionSend)
            .params(
                getParams(
                    "beginDate" to beginDate,
                    "endDate" to endDate,
                    "pageStart" to 0,
                    "pageSize" to 1000
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<UnionSend>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { bean ->
                ResponseModel(
                    summary = bean.data.summary,
                    data = ArrayList<UnionSendTotal>().apply {
                        bean.data.data.forEach { item ->
                            firstOrNull { it.sellerId == item.sellerId }
                                ?.run {
                                    products.add(
                                        UnionSendGoods(
                                            product = item.product,
                                            name = item.name,
                                            quantity = item.quantity,
                                            cost = item.cost
                                        )
                                    )
                                }
                                ?: run {
                                    add(
                                        UnionSendTotal(
                                            sellerId = item.sellerId,
                                            sellerName = item.sellerName,
                                            subTotal = item.subTotal,
                                            subQuantity = item.subQuantity,
                                            shippingFreight = item.shippingFreight,
                                            adminFreight = item.adminFreight,
                                            levelFreight = item.levelFreight,
                                            profit = item.profit,
                                            cash = item.cash,
                                            paper = item.paper,
                                            products = arrayListOf(
                                                UnionSendGoods(
                                                    product = item.product,
                                                    name = item.name,
                                                    quantity = item.quantity,
                                                    cost = item.cost
                                                )
                                            )
                                        )
                                    )
                                }
                        }
                    }
                )
            }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 配送结算明细列表
     */
    fun sendDetail(
        page: Int,
        sellerId: String,
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<Any>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<OrderModel>>(BaseUrl.unionSendDet)
            .params(
                getParams(
                    "sellerId" to sellerId,
                    "beginDate" to beginDate,
                    "endDate" to endDate,
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map {
                ArrayList<Any>().apply {
                    it.data.data.forEach { item ->
                        // 添加头部
                        add(OrderHeader().apply {
                            orderSN = item.orderSn
                            shippingSn = item.sn
                            hint = "下单时间："
                            time = item.createDate.getTimeString()
                            status_hint = item.statusDescr
                        })

                        // 添加商品
                        addItems(
                            item.shippingItems.onEach {
                                it.orderSN = item.orderSn
                                it.shippingSn = item.sn
                                it.shipId = item.id
                                it.consignee = item.consignee.orEmpty()
                                it.phone = item.phone.orEmpty()
                                it.hopeDate = item.hopeDate.orEmpty()
                                it.methodDescr = item.methodDescr.orEmpty()
                                it.fast = item.isFast
                            }
                        )

                        // 添加底部
                        add(OrderFooter().apply {
                            orderSN = item.orderSn
                            shippingSn = item.sn
                            total_num = item.quantity
                            amount = item.amount.orEmpty()
                        })
                    }
                }
            }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 空桶结算列表
     */
    fun barrelList(
        page: Int,
        beginDate: String,
        endDate: String,
        onSuccess: (UnionBarrelSummary) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ResponseBean<UnionBarrelSummary>>>(BaseUrl.unionBucSum)
            .params(
                getParams(
                    "beginDate" to beginDate,
                    "endDate" to endDate,
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseBean<UnionBarrelSummary>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data!! }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 空桶结算明细列表
     */
    fun barrelDetail(
        page: Int,
        sellerId: String,
        barrelId: String,
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<UnionBarrel>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ResponseModel<UnionBarrel>>>(BaseUrl.unionBucDet)
            .params(
                getParams(
                    "sellerId" to sellerId,
                    "barrelId" to barrelId,
                    "beginDate" to beginDate,
                    "endDate" to endDate,
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<UnionBarrel>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 收支结算统计
     */
    fun reportSettle(
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<UnionChart>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ArrayList<UnionChart>>>(BaseUrl.unionSettle)
            .params(
                getParams(
                    "beginDate" to beginDate,
                    "endDate" to endDate
                )
            )
            .converter(object : JacksonConvert<BaseResponse<ArrayList<UnionChart>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 收支结算水站列表
     */
    fun settleStation(
        page: Int,
        type: String,
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<UnionStation>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ArrayList<UnionStation>>>(BaseUrl.unionSteSta)
            .params(
                getParams(
                    "type" to type,
                    "beginDate" to beginDate,
                    "endDate" to endDate,
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JacksonConvert<BaseResponse<ArrayList<UnionStation>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 转派结算订单水站筛选列表
     */
    fun stationList(
        type: String,
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<UnionFilter>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ArrayList<UnionFilter>>>(BaseUrl.unionSteFlr)
            .params(
                getParams(
                    "type" to type,
                    "beginDate" to beginDate,
                    "endDate" to endDate
                )
            )
            .converter(object : JacksonConvert<BaseResponse<ArrayList<UnionFilter>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 转派结算订单列表
     */
    fun orderList(
        page: Int,
        type: String,
        enterpriseId: String,
        beginDate: String,
        endDate: String,
        onSuccess: (Int, ArrayList<Any>) -> Unit = { _, _ -> },
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<OrderModel>>(BaseUrl.unionSteOrd)
            .params(
                getParams(
                    "enterpriseId" to enterpriseId,
                    "type" to type,
                    "beginDate" to beginDate,
                    "endDate" to endDate,
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map {
                ArrayList<Any>().apply {
                    it.data.data.forEachIndexed { index, item ->
                        // 添加头部
                        add(OrderHeader().apply {
                            position = index
                            orderSN = item.orderSn
                            shippingSn = item.sn
                            status_hint = item.statusDescr
                            hint = "下单时间："
                            time = item.createDate.getTimeString()
                        })

                        // 添加商品
                        addItems(
                            item.shippingItems.onEach {
                                it.orderSN = item.orderSn
                                it.shippingSn = item.sn
                                it.position = index
                                it.hopeDate = item.hopeDate.orEmpty()
                                it.fast = item.isFast
                                it.first = item.isFisrst
                            }
                        )

                        // 添加底部
                        add(OrderFooter().apply {
                            position = index
                            orderSN = item.orderSn
                            shippingSn = item.sn
                            status = item.status.orEmpty()
                            total_num = item.quantity
                            amount = item.amountPaid.orEmpty()
                            amountHint = "实付款: "
                            settlementPrice = item.settlementPrice.formatDecimal()
                            name = item.consignee.orEmpty()
                            phone = item.phone.orEmpty()
                            address = item.address
                            memo = item.memo.orEmpty()
                            enterpriseName = item.enterpriseName.orEmpty()
                            adminName = item.adminName.orEmpty()
                            createDate = item.createDate.getTimeString()
                            hopeDate = item.hopeDate.getTimeString()

                            (type == "in")
                                .condition {
                                    amountHint = "结算金额: "
                                    amount = item.settlementPrice.formatDecimal()
                                }
                        })
                    }

                    add(it.data.recordsTotal)
                }
            }
            .subscribeByFinally(
                event = this,
                onSuccess = { onSuccess(it.removeLast() as Int, it) },
                onFinally = { onFinally() }
            )
    )

    /**
     * 联盟商品列表
     */
    fun goodsList(
        page: Int,
        type: String,
        enterpriseId: String,
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<HomeContent>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ArrayList<HomeContent>>>(BaseUrl.unionGoods)
            .params(
                getParams(
                    "enterpriseId" to enterpriseId,
                    "type" to type,
                    "beginDate" to beginDate,
                    "endDate" to endDate,
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JacksonConvert<BaseResponse<ArrayList<HomeContent>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 联盟商品水站筛选列表
     */
    fun goodsFilterList(
        type: String,
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<UnionFilter>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ArrayList<UnionFilter>>>(BaseUrl.unionGoodsSum)
            .params(
                getParams(
                    "type" to type,
                    "beginDate" to beginDate,
                    "endDate" to endDate
                )
            )
            .converter(object : JacksonConvert<BaseResponse<ArrayList<UnionFilter>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

}